﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WepApi07.Data;

namespace WepApi07.Domain
{
    public class EfResponsitory<T> : IResponsitory<T> where T : BaseEntity
    {
        private readonly Admin07Dbcontext db;
        public EfResponsitory(Admin07Dbcontext admin)
        {
            db = admin;
        }

        private DbSet<T> _entity;

        private DbSet<T> Entity
        {
            get
            {
                if (_entity == null)
                {
                    _entity = db.Set<T>();
                }
                return _entity;
            }
        }
        public IQueryable<T> Table 
        { get 
          {    
             return _entity;
          }
        }

        public void Delete(int id)
        {
            var row = Table.Where(x => x.Id == id).FirstOrDefault();
            Delete(row);
        }

        public void Delete(T entity)
        {
            Entity.Remove(entity);
            db.SaveChanges();
        }

        public void Insert(T entity)
        {
            Entity.Add(entity);
            db.SaveChanges();
        }

        public void InsertBulk(IEnumerable<T> entity)
        {
           
            Entity.AddRange(entity);
            db.SaveChanges();
        }

        public void Update(T entity)
        {
            Entity.Update(entity);
            db.SaveChanges();
        }

        public void Delete(IEnumerable<T> entities)
        {
            Entity.RemoveRange(entities);
            db.SaveChanges();
        }

        public T GetById(int id)
        {
            return Entity.Where(x => x.Id == id).FirstOrDefault();
        }
    }
}
